package algorithm.sort.asciiSort;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * Created by cyd on 2022-06-22 18:36:59
 * @ClassName : algorithm.TestSort.asciiSort.TestAsciiSort
 * @Description : 类描述
 */
public class TestAsciiSort {


    @Test
    public void test() {
        String foo = "1";
        String bar = "2";
        String foo_bar = null;
        String foobar = "4";
        HashMap<String, String> map = new HashMap<>();
        map.put("foo", foo);
        map.put("bar", bar);
        map.put("foo_bar", foo_bar);
        map.put("foobar", foobar);

        Map<String, String> resultMap = sortMap(map);
        resultMap.forEach((key, value) -> System.out.println(key + "---" + value));

    }


    /**
     * 将map中的数据，以键采取ascii排序
     */
    public static Map<String, String> sortMap(Map<String, String> param) {
        List<String> keyList = param.keySet().stream().collect(Collectors.toList());
        Map<String, String> result = new LinkedHashMap<>();

        List<String> listByAscii = sortByAscii(keyList);
        for (String key : listByAscii) {
            String value = param.get(key);
            result.put(key, value);
        }
        return result;
    }

    /**
     * 对字符串数组进行排序
     *
     * @param keys
     * @return
     */
    public static List<String> sortByAscii(List<String> keys) {

        for (int i = 0; i < keys.size() - 1; i++) {
            for (int j = 0; j < keys.size() - i - 1; j++) {
                String pre = keys.get(j);
                String next = keys.get(j + 1);
                if (isMoreThan(pre, next)) {
                    String temp = pre;
                    keys.set(j, next);
                    keys.set(j + 1, temp);
                }
            }
        }
        return keys;
    }

    /**
     * 比较两个字符串的大小，按字母的ASCII码比较
     *
     * @param pre
     * @param next
     * @return
     */
    private static boolean isMoreThan(String pre, String next) {
        if (null == pre || null == next || "".equals(pre) || "".equals(next)) {
            return false;
        }

        char[] c_pre = pre.toCharArray();
        char[] c_next = next.toCharArray();

        int minSize = Math.min(c_pre.length, c_next.length);

        for (int i = 0; i < minSize; i++) {
            if ((int) c_pre[i] > (int) c_next[i]) {
                return true;
            } else if ((int) c_pre[i] < (int) c_next[i]) {
                return false;
            }
        }
        if (c_pre.length > c_next.length) {
            return true;
        }

        return false;
    }
}
